import wepy from 'wepy'

const interfaces = {
  async getUserInfo() {
    const loginData = await wepy.login()
    const userinfo = await wepy.getUserInfo()
    userinfo.code = loginData.code  // userinfo 用户信息
    wx.setStorageSync('wxUserInfo', userinfo)
    return new Promise((resolve, reject) => {
      if (loginData && userinfo) {
        resolve(userinfo)
      } else {
        reject()
      }
    })
  },
  async login () {
    // debugger
    let userinfoRaw = {}
    let userinfo = {}
    let url = await wepy.getStorageSync('serverUrl')
    try {
      userinfoRaw = await interfaces.getUserInfo()
      // console.log(userinfoRaw)
      userinfo = await wepy.request({
        url: url + '/client/wxLogin/wxLoginDown4smallProgram',  // 微信登录地址
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          'code': userinfoRaw.code,
          'encryptedData': userinfoRaw.encryptedData,
          'iv': userinfoRaw.iv,
          'userInfo': JSON.stringify(userinfoRaw.userInfo)
        }
      })
      // console.log('userinfo', userinfo)
      // if (!userinfo.data.data.phone) {
      //   // 手机号为空
      //   console.log('手机号为空')
      //   wx.redirectTo({
      //     url: '/pages/mine/initAccount'
      //   })
      // }
      await wepy.setStorage({   // 将获取回来的session放入本地存储中
        key: '_session',
        data: userinfo.data.data.sessionId
      })
      await wepy.setStorage({   // 将获取回来的用户信息放入本地存储中
        key: 'userInfo',
        data: userinfo.data.data
      })

    } catch (e) {
      wepy.showModal({
        title: '提示',
        content: `获取用户信息失败，请关闭重新进入。${e.message}`
      })
    }
  }
}

export default interfaces
